package com.onland.dfish.controller;

import com.alibaba.fastjson.JSONObject;
import com.onland.dfish.entity.Users;
import com.onland.dfish.entity.Videos;
import com.onland.dfish.service.IUsersService;
import com.onland.dfish.util.DateTimeUtils;
import com.onland.dfish.util.RandomCodeUtils;
import com.onland.dfish.util.SignUtils;
import com.onland.dfish.util.TimesUtils;
import com.onland.dfish.util.mail.EmailService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 处理会员用户业务请求控制器类
 */
@Controller
@RequestMapping("user")
public class UsersController {
    @Autowired
    private IUsersService usersService;

    /**
     * 检查邮箱是否被注册
     *
     * @param email
     * @return
     */
    @PostMapping("check_email")
    @ResponseBody
    public int checkEmail(String email, HttpSession session) throws Exception {
        int count = usersService.countByEmail(email);
        if (0 == count) {
            //该邮箱没有被注册,发送注册验证码
            //邮件主题
            String title = "注册验证码";
            //随机邮件验证码
            String codes = RandomCodeUtils.getCheckCode();
            //将邮件验证码添加到会话中(后面项目保存到Redis中)
            session.setAttribute("mail_codes", codes);
            //邮件的主体或内容
            String content = "欢迎注册抖鱼网会员,您的注册验证码是:<span style='color:#0000FF;font-size:28px'>" + codes + "</span>";
            EmailService.sentMailHtml(title, content, email);
        }
        return count;
    }

    /**
     * 用户注册
     *
     * @param email      邮箱
     * @param codes      邮件验证码
     * @param password   密码
     * @param confirmPwd 确认密码
     * @param session
     * @return
     */
    @PostMapping("register")
    public String register(String email, String codes, String password, String confirmPwd, HttpSession session) {
        //检验用户填写的验证码是否正确
        String codesLib = (String) session.getAttribute("mail_codes");
        if (codesLib == null) {
            //验证码已过期或失效
            return "redirect:/user/register_fail.jsp?state=10";
        }
        if (!codesLib.equalsIgnoreCase(codes)) {
            //邮件验证码错误
            return "redirect:/user/register_fail.jsp?state=11";
        }
        //后台数据验证(略)
        //添加会员用户记录
        int rows = usersService.createUsers(email, password);
        //注册成功,跳转登录页面
        return "redirect:/user/login_user.jsp";
    }

    @RequestMapping("login")
    @ResponseBody
    public Users login(String email, String password, HttpSession session) {
        Users users = usersService.login(email, password);
        if (users != null) {
            session.setAttribute("users", users);
        }
        return users;
    }

    /**
     * 根据id查询用户信息
     *
     * @param id
     * @return
     */
    @RequestMapping("load_one")
    public String selectOne(int id, HttpServletRequest req) {
        Users users = usersService.selectById(id);
        req.setAttribute("users", users);
        return "/user/user_center.jsp";
    }

    /**
     * 修改用户资料
     *
     * @param users
     * @return
     */
    @RequestMapping("update")
    public String updateUser(Users users) {
        int rows = usersService.updateUser(users);
        return "redirect:/user/updateUser_result.jsp?rows=" + rows;
    }

    /**
     * 根据id修改密码
     *
     * @param users
     * @return
     */
    @RequestMapping("update_pwd")
    public String updateUserPwd(Users users) {
        int rows = usersService.UpUserPasswd(users);
        return "redirect:/user/UpPwd_result.jsp?rows=" + rows;
    }

    /**
     * 发送忘记密码验证码
     *
     * @param email
     * @param session
     * @return
     * @throws Exception
     */
    @PostMapping("update_password_code")
    @ResponseBody
    public int updatePasswordCode(String email, HttpSession session) throws Exception {
        int count = usersService.countByEmail(email);
        if (1 == count) {
            String title = "忘记密码验证码";
            String codes = RandomCodeUtils.getCheckCode();
            session.setAttribute("mail_codes", codes);
            String content = "您的验证码是:<span style='color:#0000FF;font-size:28px'>" + codes + "</span>";
            EmailService.sentMailHtml(title, content, email);
        }
        return count;
    }

    /**
     * 验证验证码是否正确
     *
     * @param codes
     * @param session
     * @return
     */
    @PostMapping("check_codes")
    public String checkCodes(@RequestParam String codes, @RequestParam String email, HttpSession session) {
        String codesTemp = (String) session.getAttribute("mail_codes");
        if (codesTemp == null) {
            //验证码已过期
            return "redirect:/user/find_pwd_result.jsp?status=404";
        }
        if (!codesTemp.equalsIgnoreCase(codes)) {
            //验证码错误;
            return "redirect:/user/find_pwd_result.jsp?status=401";
        }
        //签名参数
        // 随机字符串
        String rdStr = RandomCodeUtils.bulidRepeatCodes(128);
        //链接超时
        long timeout = SignUtils.getTimeExpire(5);

        //签名
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("email", email);
        paramMap.put("rd_str", rdStr);
        paramMap.put("timeout", String.valueOf(timeout));
        String sign = SignUtils.getSign(paramMap);
        return "redirect:/user/update_password_by_code.jsp?email=" + email + "&rd_str=" + rdStr + "&timeout=" + timeout + "&sign=" + sign;
    }

    /**
     * 找回密码
     *
     * @param password
     * @return
     */
    @RequestMapping("update_password_by_code")
    public String updatePasswordByCode(@RequestParam String password, @RequestParam String email, @RequestParam("rd_str") String rdStr, @RequestParam long timeout, @RequestParam String sign) {
         long now=System.currentTimeMillis();
         if(now>=timeout)
         {
             //已超时
             return "redirect:/user/find_pwd_result.jsp?status=409";
         }
        Map<String, String> paramMap = new HashMap<>();
        paramMap.put("email", email);
        paramMap.put("rd_str", rdStr);
        paramMap.put("timeout", String.valueOf(timeout));
        String newSign = SignUtils.getSign(paramMap);
        if(!newSign.equals(sign)){
            //签名错误
            return "redirect:/user/find_pwd_result.jsp?status=405";
        }
        int  rows=usersService.updatePasswordByCode(password, email);
        return "redirect:/user/find_pwd_result.jsp?status="+rows;
    }

    @GetMapping("exit")
    public String exit(HttpSession session) {
        session.invalidate();
        return "redirect:/user/login_user.jsp";
    }

    /**
     * 查询关注
     *
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping("queryLike")
    public String queryLike(int userId, HttpServletRequest request) {
        List<Users> usersList = usersService.queryLike(userId);
        request.setAttribute("usersList", usersList);
        return "/user/my_like.jsp";
    }

    /**
     * 查询粉丝
     *
     * @param userId
     * @param request
     * @return
     */
    @RequestMapping("queryFans")
    public String queryFans(int userId, HttpServletRequest request) {
        List<Users> usersList = usersService.queryFans(userId);
        request.setAttribute("usersList", usersList);
        return "/user/my_fans.jsp";
    }

}
